<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <button onclick="routerHistory.push('/')">首页</button>
    <button onclick="routerHistory.push('/about')">关于我</button>
    <button onclick="routerHistory.replace('/user')">替换</button>
  </body>
  <script>
    /**
     * back: 上一个路由地址
     * current: 当前的路由地址
     * forward: 要跳转的路由地址
     * replace: 是否替换(不生成历史记录)
     * computedScroll: 页面位置
     */
    function buildState(
      back,
      current,
      forward,
      replace = false,
      computedScroll = false
    ) {
      return {
        back,
        current,
        forward,
        replace,
        scroll: computedScroll
          ? { left: window.pageXOffset, top: window.pageYOffset }
          : null,
        position: window.history.length - 1, // 历史记录，浏览器默认会有一条
      };
    }

    function createCurrentLocation() {
      const { pathname, search, hash } = window.location;
      return pathname + search + hash;
    }

    function useHistoryStateNavigation() {
      const currentLocation = {
        value: createCurrentLocation(),
      };
      const historyState = {
        value: window.history.state,
      };
      // 第一次刷新页面 此时没有任何状态，那么我就自己维护一个状态
      //（后退后是哪个路径、当前路径是哪个、要去哪里，我是用的push跳转还是replace跳转，跳转后滚动条位置是哪）
      if (!historyState.value) {
        changeLocation(
          currentLocation.value,
          buildState(null, currentLocation.value, null, true),
          true
        );
      }

      function changeLocation(to, state, replace) {
        const url = to;
        window.history[replace ? "replaceState" : "pushState"](
          state,
          null,
          url
        );
        historyState.value = state; // 将自己生成的状态同步到了 路由系统中了
      }
    }

    function createWebHistory() {
      const historyNavigation = useHistoryStateNavigation();
    }

    const routerHistory = createWebHistory();
  </script>
</html>
